package smsweb.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import smsweb.client.SmsService;
import smsweb.client.Util;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class SmsServiceImpl extends RemoteServiceServlet implements SmsService {

	@Override
	public void addSms(String address, String message) {
		PersistenceManager pm = getPersistenceManager();
		try {
			long id = System.currentTimeMillis();
			Key key = KeyFactory.createKey(Sms.class.getSimpleName(), id);
			Sms sms = new Sms();
			sms.setKey(key);
			sms.setAddress(address);
			sms.setMessage(message);
			sms.setDate(new Date(id));
			sms.setId(id);
			sms.setIncomingMessage(false);
			sms.setRead(false);
			sms.setSent(false);
			pm.makePersistent(sms);
		} finally {
			pm.close();
		}

	}

	private PersistenceManager getPersistenceManager() {
		return Util.getPMF().getPersistenceManager();
	}

	@Override
	public List<String[]> getAllMessage() {
		PersistenceManager pm = getPersistenceManager();
		List<String[]> retVal = new ArrayList<String[]>();
		try{
			Query query = pm.newQuery(Sms.class);
			query.setFilter("read == false && incomming == true");
			query.setOrdering("date asc");
			List<Sms> results = (List<Sms>) query.execute();
			String[] row = null;
			for(Sms sms : results){
				row = new String[3];
				row[0] = sms.getAddress();
				row[1] = sms.getMessage();
				row[2] = "" + sms.getDate().getTime();
				retVal.add(row);
			}
			
		}finally{
			pm.close();
		}
		return null;
	}
}
